﻿using Extentions;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using TrainingReminderSystem.Dal;
using TrainingReminderSystem.Model;

namespace TrainingReminderSystem.Bll
{
    /// <summary>
    /// 配置文件Bll
    /// </summary>
    public partial class SysSettingBll : PcLoginedBll
    {
        #region 基础属性

        private static string _fullJson = null;

        /// <summary>
        /// json文件的所有字符串缓存
        /// </summary>
        private static string FullJson
        {
            get
            {
                if (_fullJson != null) return _fullJson;
                var fileFullName = Base64Helper.CurrentDirectory + "data/parameterInfo.json";
                using (StreamReader sr = new StreamReader(fileFullName, Encoding.UTF8))
                {
                    _fullJson = sr.ReadToEnd();
                    return _fullJson;
                }
            }
        }

        #endregion

        #region 获取单条配置

        ///// <summary>
        ///// 获取单条配置
        ///// </summary>
        ///// <param name="code"></param>
        ///// <param name="sysStoreID"></param>
        ///// <returns></returns>
        //public static SysSetting GetModel(EnumSettingCode code, int sysStoreID)
        //{
        //    using (var db = Db)
        //    {
        //        return GetModel(code, sysStoreID, db);
        //    }
        //}

        /// <summary>
        /// 获取单条配置
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static SysSetting GetModel(EnumSettingCode code)
        {
            using (var db = Db)
            {
                return GetModel(code, CurrentStore.SysStoreID, db);
            }
        }

        private static object _sycn = new object();

        /// <summary>
        /// 得到配置参数方法, 带读取默认文件
        /// </summary>
        /// <param name="code"></param>
        /// <param name="sysStoreID"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal static SysSetting GetModel(EnumSettingCode code, int sysStoreID, DbEntities db)
        {
            lock (_sycn)
            {
                try
                {
                    var key = "EnumSettingCode" + sysStoreID.ToString() + code.ToString();
                    SysSetting sysSetting = CacheHelper.GetCache(key) as SysSetting;
                    if (sysSetting != null) return sysSetting;
                    if (db == null) return new SysSetting();
                    var model = db.SysSetting.FirstOrDefault(m =>
                        m.EnumSettingCode == code && m.SysStoreID == sysStoreID);
                    const int min = 1;
                    if (model != null)
                    {
                        CacheHelper.SetAbsoluteCache(key, model, min);
                        return model;
                    }

                    JArray jarray = JsonHelper.DeserializeObject<object>(FullJson) as JArray;
                    if (jarray == null) return null;
                    foreach (JToken item in jarray)
                    {
                        JArray jaarayChildren = item["Children"] as JArray;
                        if (jaarayChildren != null)
                        {
                            foreach (JToken child in jaarayChildren)
                            {
                                if (child["EnumSettingCode"].ToString() == ((int)code).ToString())
                                {
                                    model = JsonHelper.DeserializeObject<SysSetting>(child.ExToJson());
                                    model.Value = child["Value"].ToString();
                                    CacheHelper.SetAbsoluteCache(key, model, min);
                                    return model;
                                }
                            }
                        }
                    }

                    return null;
                }
                catch (Exception ex)
                {
                    ex.ExLogError("获取配置报错");
                    return null;
                }
            }
        }

        #endregion

        #region 验证保存配置

        public bool Validate(SysSetting model, out string msg, bool isAdd, DbEntities db)
        {
            msg = string.Empty;
            if (model == null)
            {
                msg = "提交数据出错,请刷新后重试!";
                return false;
            }

            if (string.IsNullOrEmpty(model.SysSettingName))
            {
                msg = "配置名称为空";
                return false;
            }
            //if (string.IsNullOrEmpty(model.Value))
            //{
            //    msg = "值不能为空!";
            //    return false;
            //}
            if (model.Value == null) model.Value = string.Empty;//model.Value ??= string.Empty;
            model.PY = ToolHelper.GetPy(model.SysSettingName);
            //if (model.EnumSettingCode == EnumSettingCode.项目1 || model.EnumSettingCode == EnumSettingCode.项目2 || model.EnumSettingCode == EnumSettingCode.项目3)
            //{
            //    int val = model.Value.ExToInt32();
            //    if (val > 0)
            //    {
            //        var tempR = new CustomerPrizeDrawRecordBll().GetCustomerPrizeDraw(db, null);
            //        if (tempR.Success == false)
            //        {
            //            msg = "此设置与平台自营活动相关:" + tempR.Message;
            //            return false;
            //        }

            //        var detail = tempR.Result.PrizeDrawActivityDetail.FirstOrDefault(m => m.GoodsID == val);
            //        if (detail == null)
            //        {
            //            msg = "此设置与平台自营活动相关:" + "此项目未设置在平台自营活动奖品中,请核查";
            //            return false;
            //        }
            //    }
            //}

            model.SysStoreID = CurrentStore.SysStoreID;
            model.UpdateSysEmployeeID = CurrentEmployee?.SysEmployeeID;
            model.UpdateDate = DateTime.Now;
            return true;
        }

        public AjaxResult<dynamic> Save(SysSetting model)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            string msg;
            using (var db = Db)
            {
                if (!Validate(model, out msg, false, db))
                {
                    r.Message = msg;
                    return r;
                }
                var beforeModel = db.SysSetting.FirstOrDefault(m => m.ID == model.ID);
                if (beforeModel == null)
                {
                    string error = AddLog(db, model, EnumLogType.新建);
                    if (!string.IsNullOrEmpty(error))
                    {
                        return AjaxResult<dynamic>.ErrorResult(error);
                    }
                    db.SysSetting.Add(model);
                }
                else
                {
                    string error = AddLog(db, model, EnumLogType.编辑);
                    if (!string.IsNullOrEmpty(error))
                    {
                        return AjaxResult<dynamic>.ErrorResult(error);
                    }
                    beforeModel.UpdateSysEmployeeID = model.UpdateSysEmployeeID;
                    beforeModel.UpdateDate = model.UpdateDate;
                    beforeModel.SysSettingName = model.SysSettingName;
                    beforeModel.Value = model.Value;
                }
                var isSuccess = db.SaveChanges() >= 0;
                var key = "EnumSettingCode" + model.EnumSettingCode.ToString();
                CacheHelper.RemoveCache(key);
                r.Success = isSuccess;
                r.Message = isSuccess ? "操作成功" : "操作失败,请重试!";
                r.Result = model.ID;
                return r;
            }
        }

        #endregion

        #region 得到集合

        /// <summary>
        /// 得到集合
        /// </summary>
        /// <param name="enumSettintType"></param>
        /// <returns></returns>
        public AjaxResult<List<SysSetting>> GetListByType(EnumSettingType enumSettintType)
        {
            using (var db = Db)
            {
                var list = db.SysSetting.Where(m => m.EnumSettingType == enumSettintType).ToList();
                List<SysSetting> listResult = GetFileDefaultData().FirstOrDefault(m => m.EnumSettingType == enumSettintType)
                    .Children;
                foreach (var item in listResult)
                {
                    item.DefaultValue = item.Value;
                    var first = list.FirstOrDefault(m => m.EnumSettingCode == item.EnumSettingCode);
                    if (first != null)
                    {
                        item.Value = first.Value;
                        item.ID = first.ID;
                    }
                }
                return AjaxResult<List<SysSetting>>.SuccessResult(listResult);
            }
        }

        #endregion

        #region 得到默认配置

        /// <summary>
        /// 得到默认配置
        /// </summary>
        /// <returns></returns>
        private List<ParameterInfoJson> GetFileDefaultData()
        {
            string json = FullJson;
            var obj = JsonHelper.DeserializeObject<List<ParameterInfoJson>>(json);
            obj = obj.Where(m => m.IsDel == false).ToList();
            foreach (var item in obj)
            {
                if (item.Children != null) item.Children = item.Children.Where(m => m.IsDel == false).ToList();
            }

            return obj;
        }

        /// <summary>
        /// 配置类
        /// </summary>
        private class ParameterInfoJson
        {
            public EnumSettingType EnumSettingType { get; set; }

            public EnumSettingCode EnumSettingCode { get; set; }

            public string EnumSettingTypeName { get; set; }

            public bool IsDel { get; set; }

            public List<SysSetting> Children { get; set; }
        }

        #endregion
    }
}
